/*
 * Copyright 2022-2027 中国信息通信研究院云计算与大数据研究所
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package com.common.schedule;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.constant.ClusterConstant;
import com.common.fastjson.JsonResult;
import com.localMapper.ClustercfgMapper;
import com.pojo.Clustercfg;

@Component
@Configuration // 1.主要用于标记配置类，兼备Component的效果。
public class HeartbeatSchedule {
	private final Logger logger = LoggerFactory.getLogger(HeartbeatSchedule.class);
	public static boolean isMaster = false;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ClustercfgMapper clustercfgMapper;

	@Scheduled(cron = "*/5 * * * * ?")
	private void moveTranlog() {
		if(!isMaster) {
//			System.out.println("所分配内存的剩余大小："+Runtime.getRuntime().totalMemory()/(1024*1024)+"M");
//			System.out.println("当前未使用的内存大小："+Runtime.getRuntime().freeMemory()/(1024*1024)+"M");
//			System.out.println("可以获得的最大内存"+Runtime.getRuntime().maxMemory()/(1024*1024)+"M");
//			System.out.println("当前使用的内存大小："+(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/(1024*1024)+"M");
			return;
		}
		List<Clustercfg> clusterList = clustercfgMapper.getClustercfg();
		Map<String, Clustercfg> slaveMap = new HashMap<String, Clustercfg>();
		Clustercfg master = null;
		for (Clustercfg clustercfg : clusterList) {
			if (ClusterConstant.CLUSTER_SLAVE.equals(clustercfg.getCluster_type())) {
				slaveMap.put(clustercfg.getCluster_id(), clustercfg);
			} else if (ClusterConstant.CLUSTER_MASTER.equals(clustercfg.getCluster_type())) {
				master = clustercfg;
			}
		}
		if (master == null || slaveMap.size() < 1) {
			return;
		}
		master.setCluster_stat(ClusterConstant.SLAVE_SUCCESS);
		clustercfgMapper.updateClustercfg(master);
		for (String clustercfg : slaveMap.keySet()) {
			try {
				JSONObject json = new JSONObject();
        		HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(JSON.parseObject(json.toJSONString()), headers);
            	logger.info(" HeartbeatSchedule send slave {} ",json.toJSONString());
                HttpEntity<String> resultObj = restTemplate.exchange(slaveMap.get(clustercfg).getCluster_url()+"heartbeat", HttpMethod.POST, entity, String.class);
        		JsonResult jsonResult = JSON.parseObject(resultObj.getBody(), JsonResult.class);
            	logger.info(" HeartbeatSchedule result slave {} ",jsonResult.toString());
        		if(jsonResult.getCode()==0) {
        			slaveMap.get(clustercfg).setCluster_stat(ClusterConstant.SLAVE_SUCCESS);
        			clustercfgMapper.updateClustercfg(slaveMap.get(clustercfg));
        		}else {
        			slaveMap.get(clustercfg).setCluster_stat(ClusterConstant.SLAVE_FAILURE);
        			clustercfgMapper.updateClustercfg(slaveMap.get(clustercfg));
        		}
			} catch (Exception e) {
				logger.error(" HeartbeatSchedule send slave is error {} ", e.getMessage());
			}
		}
	}
}
